package com.will.yuaiagent.rag;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @author will
 * @since 2025/7/9 16:10
 * 自定义查询翻译器（用第三方API减少花销）
 */
@Component
public class QueryTranslationRewriter {

    @Value("${baiduTranslate.appId}")
    private String appid;
    @Value("${baiduTranslate.key}")
    private String key;

    public String doQueryTranslation(String query) {

        HttpClient httpClient = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();

        String url = "https://fanyi-api.baidu.com/api/trans/vip/translate";
        String salt = String.valueOf(new Random(100));
        String sign = appid + query + salt + key;
        sign = MD5.create().digestHex(sign);
        String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8);
        String queryString = "?q=" + encodedQuery + "&from=auto&to=en&appid=" + appid + "&salt=" + salt + "&sign=" + sign;
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url + queryString))
                .GET()
                .build();
        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            JSONObject jsonObject = new JSONObject(response.body());
            String translatedText = jsonObject.getJSONArray("trans_result").getJSONObject(0).getStr("dst");
            return translatedText;
        } catch (IOException | InterruptedException e) {
            System.err.println("HTTP 请求失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("网络请求失败，请检查网络连接或目标地址是否可达。", e);
        }
    }
}
